package cn.wenjie.gd.dao;

import java.util.ArrayList;
import java.util.List;

import cn.wenjie.gd.domain.Role;
import cn.wenjie.gd.domain.User;
import cn.wenjie.gd.util.UserPage;
import cn.wj.base.dao.BaseDaoImp;

public class UserDaoImp extends BaseDaoImp<User,Integer> implements UserDao {

	@Override
	public Class<User> getEntryClass() {
		return User.class;
	}

	@Override
	public User findUser(String loginName, String password) {
		String parm[]={loginName,password};
		return (User) queryForObject("SELECT * FROM USER u WHERE u.loginName=? AND u.password=? ", getEntryClass(),parm);
	}

	@Override
	public boolean checkUserName(String login_name) {
		String parm[]={login_name};
		List<User> u=query("SELECT * FROM USER u WHERE u.loginName=? ", getEntryClass(),parm);
		if(u!=null && u.size()>0) return true;
		return false;
	}

	@Override
	public List<Role> getAllRole() {
		String parm[]={};
		return query("SELECT * FROM role ", Role.class);
	}

	@Override
	public UserPage getPageList(UserPage page) {
		StringBuffer sqlbody=new StringBuffer();
		List list=new ArrayList();
		sqlbody.append("  FROM USER u WHERE 1=1 ");
		if(page.getName()!=null && !page.getName().equals("")){
			sqlbody.append("  AND  u.name LIKE '%"+page.getName()+"%' ");
		}
		if(page.getSex()!=null && page.getSex()!=0 ){
			sqlbody.append(" AND u.sex=? ");
			list.add(page.getSex());
		}
		if(page.getRole()!=null){
			sqlbody.append(" AND u.role=? ");
			list.add(page.getRole());
		}
		
		
		StringBuffer getCountSql=new StringBuffer();
		StringBuffer sql=new StringBuffer();
		
		getCountSql.append(" SELECT COUNT(*) ");
		getCountSql.append(sqlbody);
		sql.append(" SELECT * ");
		sql.append(sqlbody);
		sql.append(" LIMIT ?,? ");
		
		int count =queryForInt(getCountSql.toString(), list.toArray());
		page.setTotalRecord(count);
		list.add(page.getStartIndex());
		list.add(page.getPageSize());
		
		List<User> userList=query(sql.toString(), getEntryClass(), list.toArray());
		page.setResult(userList);
		return page;
	}

	@Override
	public List<User> getAllMember() {
		return query("SELECT u.id,u.cardId FROM USER u WHERE u.role=1",User.class);
	}
	
}
